package com.thatvn.diemtinvietnam;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.SuppressLint;
import android.util.Log;
import android.util.JsonReader;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.thatvn.diemtinvietnam.MainActivity;

public class jsonParse {	   
	   private String id = "id";
	   private String title = "title";
	   private String date = "date";
	   private String image = "image";
	   private String link = "link";
	   private String source = "maindomain";
	   private String ranking = "ranking";
	   private String catid = "catid";
	   private String timediff = "timediff";
	   private String hasContent = "hasContent";
	   private String nameRelated = "nameRelated";
	   private String linkRelated = "linkRelated";
	   private String sourceRelated = "maindomainRelated";
	   private String idRelated = "idRelated";
	   private String imageRelated = "imageRelated";
	   private String hasContentRelated = "hasContentRelated";
	   
	   private String urlString = null;
	   
	   
	   public volatile boolean parsingComplete = true;
	   public ArrayList<HashMap<String, String>> itemNewsList;
	   public ArrayList<Object> itemNewsListChild;
	   //public ArrayList<HashMap<Object, Object>> itemNewsListChildDetail;
	   
	   public jsonParse(String url){
	      this.urlString = url;
	   }
	   public String getTitle(){
	      return title;
	   }
	   public String getImage(){
	      return image;
	   }
	   public ArrayList<HashMap<String, String>> getItemNewsList(){
		   return itemNewsList;
	   }
	   public ArrayList<Object> getItemNewsListChild(){
		   return itemNewsListChild;
	   }
	   
	   @SuppressLint("NewApi")
	   public void readAndParseJSON(String in) {
		  JSONArray items = null; 
		  //String preTitle="";
	      try {
	    	  JSONObject jsonObj = new JSONObject(in);
           
           // Getting JSON Array node
	    	  items = jsonObj.getJSONArray("news");	    	  
	    	  //Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", String.valueOf(items.length()));
	    	  itemNewsList = new ArrayList<HashMap<String, String>>();
	    	  itemNewsListChild = new ArrayList<Object>();
	    	  //Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "ok2");
           // looping through All Contacts
	    	  String preTitle="";
	    	  //Init
	    	  ArrayList<HashMap<String, String>> arrChild=new  ArrayList<HashMap<String, String>>();
	    	  HashMap<String, String> itemDetailChild = new HashMap<String, String>();
	    	  //itemDetailChild.put(MainActivity.KEY_NAMERELATED, "-1");
           //itemDetailChild.put(MainActivity.KEY_LINKRELATED, "-1");
           //itemDetailChild.put(MainActivity.KEY_SOURCERELATED, "-1");
//           itemDetailChild.put(MainActivity.KEY_IDRELATED, "-1");
//           itemDetailChild.put(MainActivity.KEY_IMAGERELATED, "");
           //arrChild.add(itemDetailChild);
           for (int i = 0; i < items.length(); i++) {
               
               try{
             	  JSONObject c = items.getJSONObject(i);
                   if (c.isNull("id")) continue;
                   //Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "ok3");
                   //DOC TIN CHINH THUC
	                  id=  c.getString(MainActivity.KEY_ID); 
	                  title = c.getString(MainActivity.KEY_TITLE);
	                  if (!c.isNull("image")){
	                	  image = c.getString(MainActivity.KEY_IMAGE);
	                	  image=image.replace(" ", "%20");
	                  }else {image="";}
	                  link=c.getString(MainActivity.KEY_LINK); 
	                  source=c.getString(MainActivity.KEY_SOURCE); 
	                  date=c.getString(MainActivity.KEY_DATE);
	                  ranking=c.getString(MainActivity.KEY_RANKING);
	                  catid=c.getString(MainActivity.KEY_CATID);
	                 // Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "ok31111111111");
	                  timediff=c.getString(MainActivity.KEY_TIMEDIFF);
	                  hasContent=c.getString(MainActivity.KEY_HASCONTENT);
	                  
	                  HashMap<String, String> itemDetail = new HashMap<String, String>();
	                  
	                  //Them cho tin chinh
	                  if (title!=null && !title.isEmpty() && !title.equals(preTitle)){
	                	  if (arrChild.size()>0) itemNewsListChild.add(arrChild);
	                	  
	                	  //Log.e("aaaa", "12"+title+","+preTitle);
		                  itemDetail.put(MainActivity.KEY_ID, id);
		                  //Log.e("aaaa", "1222222");
		                  itemDetail.put(MainActivity.KEY_TITLE, title);
		                  itemDetail.put(MainActivity.KEY_IMAGE, image);
		                  itemDetail.put(MainActivity.KEY_LINK, link);
		                  itemDetail.put(MainActivity.KEY_SOURCE, source);
		                  //Log.e("aaaa", "1333333");
		                  itemDetail.put(MainActivity.KEY_DATE, date);
		                  itemDetail.put(MainActivity.KEY_RANKING, ranking);
		                  itemDetail.put(MainActivity.KEY_CATID, catid);
		                  itemDetail.put(MainActivity.KEY_TIMEDIFF, timediff);
		                  itemDetail.put(MainActivity.KEY_HASCONTENT, hasContent);
		                  itemNewsList.add(itemDetail);
		                 
		                  //Log.e("aaaa", "14444444444");
		                  itemDetailChild = new HashMap<String, String>();
		                  arrChild=new  ArrayList<HashMap<String, String>>();
		                	//Init new first child
			                  if (!c.isNull("nameRelated")){
	    	                	  nameRelated = c.getString(MainActivity.KEY_NAMERELATED);
	    	                	  linkRelated=c.getString(MainActivity.KEY_LINKRELATED);
	    		                  sourceRelated=c.getString(MainActivity.KEY_SOURCERELATED);
	    		                  idRelated=c.getString(MainActivity.KEY_IDRELATED);
	    		                  if (!c.isNull("imageRelated")){
	    		                	  imageRelated=c.getString(MainActivity.KEY_IMAGERELATED);
	    		                  }else{
	    		                	  imageRelated="";
	    		                  }
	    		                  hasContentRelated=c.getString(MainActivity.KEY_HASCONTENTRELATED);
	    		                  itemDetailChild.put(MainActivity.KEY_NAMERELATED, nameRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_LINKRELATED, linkRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_SOURCERELATED, sourceRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_IDRELATED, idRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_IMAGERELATED, imageRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_HASCONTENTRELATED, hasContentRelated);
	    		                  
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    	                  }else {
//	    		                  itemDetailChild.put(MainActivity.KEY_NAMERELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_LINKRELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_SOURCERELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_IDRELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_IMAGERELATED, "");
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    		                  //itemNewsListChildDetail.;	    		                 
	    	                  }
			                 
	                  }else{
	                	  if(title.equals(preTitle)){
	                		  if (!c.isNull("nameRelated")){
	    	                	  nameRelated = c.getString(MainActivity.KEY_NAMERELATED);
	    	                	  linkRelated=c.getString(MainActivity.KEY_LINKRELATED);
	    		                  sourceRelated=c.getString(MainActivity.KEY_SOURCERELATED);
	    		                  idRelated=c.getString(MainActivity.KEY_IDRELATED);
	    		                  if (!c.isNull("imageRelated")){
	    		                	  imageRelated=c.getString(MainActivity.KEY_IMAGERELATED);
	    		                  }else{
	    		                	  imageRelated="";
	    		                  }
	    		                  hasContentRelated=c.getString(MainActivity.KEY_HASCONTENTRELATED);
	    		                  itemDetailChild.put(MainActivity.KEY_NAMERELATED, nameRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_LINKRELATED, linkRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_SOURCERELATED, sourceRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_IDRELATED, idRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_IMAGERELATED, imageRelated);
	    		                  itemDetailChild.put(MainActivity.KEY_HASCONTENTRELATED, hasContentRelated);
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    	                  }else {
//	    		                  itemDetailChild.put(MainActivity.KEY_NAMERELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_LINKRELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_SOURCERELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_IDRELATED, "-1");
//	    		                  itemDetailChild.put(MainActivity.KEY_IMAGERELATED, "");
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    		                  //itemNewsListChildDetail.;	    		                 
	    	                  }
	                		  
	                	  }
	                  }
	                  //Log.e("aaaa", "22222222");
	                  preTitle=title;
	                  
	                  //Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "ok4");
	                  //DOC TIN LIEN QUAN
	                  
	                  
	                 
	                  
	                  //Log.e("aaaa", "111111");
	                 
	                 
	                  //Log.e("itemDetail.put", "itemDetail.put");
	                  // adding contact to contact list
	                  
	                  
	                  //Log.e("aaaa", "BBBBBBBBBBBBBBBBBBBBBBBB");
               }catch(Exception ex)
               {
             	  //Log.e("ExceptionExceptionExceptionExceptionExceptionException", ex.toString());
               }
           }
	         parsingComplete = false;
	         arrChild.add(itemDetailChild);
	         if (arrChild.size()>0) itemNewsListChild.add(arrChild);


	        } catch (Exception e) {
	           // TODO Auto-generated catch block
	        	//Log.e("ExceptionExceptionExceptionExceptionExceptionException", e.toString());
	           e.printStackTrace();
	        }

	   }
	   public String fetchJSON() throws IOException{
	      
	         try {
	            URL url = new URL(urlString);
	            //Log.e("fetchJSON", urlString);
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            conn.setReadTimeout(10000 /* milliseconds */);
	            conn.setConnectTimeout(15000 /* milliseconds */);
	            conn.setRequestMethod("GET");
	            conn.setDoInput(true);
	            //conn.setRequestProperty(field, newValue)
	            // Starts the query
	            conn.connect();
	            //Log.e("fetchJSON", "ok1");
		         //InputStream stream = conn.getInputStream();
	            InputStreamReader reader = null;
		         StringBuilder builder = new StringBuilder();
	
		         try {
		             // ...
		             reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
		             char[] buffer = new char[8192];
	
		             for (int length = 0; (length = reader.read(buffer)) > 0;) {
		                 builder.append(buffer, 0, length);
		                 
		             }
		         } finally {
		             if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
		         }
	
		         String html = builder.toString();
		         
		         String data = html;//convertStreamToString(stream);
	      		 data="{\"news\":"+data+"}";
	      		 //Log.e("fetchJSON", data);
	      		 readAndParseJSON(data);
	      		 //stream.close();
	      		 return data;
	         } catch (Exception e) {
	            e.printStackTrace();
	            return "0";
	         }	         
	      		
	   }
	   static String convertStreamToString(java.io.InputStream is) {
	      java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
	      return s.hasNext() ? s.next() : "";
	   }
}
